package utils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/31 15:45
 * @description: 二叉树节点工具类（优化空节点显示）
 */
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    /**
     * 根据层序序列构建二叉树
     *
     * @param levelOrder 层序序列数组（-1表示空节点）
     * @return 构建好的二叉树根节点
     */
    public static TreeNode buildTree(int[] levelOrder) {
        if (levelOrder == null || levelOrder.length == 0) {
            return null;
        }

        TreeNode root = new TreeNode(levelOrder[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int index = 1;

        while (!queue.isEmpty() && index < levelOrder.length) {
            TreeNode curr = queue.poll();

            // 处理左子节点
            if (index < levelOrder.length && levelOrder[index] != -1) {
                curr.left = new TreeNode(levelOrder[index]);
                queue.offer(curr.left);
            }
            index++;

            // 处理右子节点
            if (index < levelOrder.length && levelOrder[index] != -1) {
                curr.right = new TreeNode(levelOrder[index]);
                queue.offer(curr.right);
            }
            index++;
        }

        return root;
    }

    /**
     * 根据层序序列构建二叉树
     *
     * @param levelOrder 层序序列数组
     * @param tag 空结点标识
     * @return 构建好的二叉树根节点
     */
    public static TreeNode buildTree(int[] levelOrder,int tag) {
        if (levelOrder == null || levelOrder.length == 0) {
            return null;
        }

        TreeNode root = new TreeNode(levelOrder[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int index = 1;

        while (!queue.isEmpty() && index < levelOrder.length) {
            TreeNode curr = queue.poll();

            // 处理左子节点
            if (index < levelOrder.length && levelOrder[index] != tag) {
                curr.left = new TreeNode(levelOrder[index]);
                queue.offer(curr.left);
            }
            index++;

            // 处理右子节点
            if (index < levelOrder.length && levelOrder[index] != tag) {
                curr.right = new TreeNode(levelOrder[index]);
                queue.offer(curr.right);
            }
            index++;
        }

        return root;
    }

    // 用于获得树的层数
    public static int getTreeDepth(TreeNode root) {
        return root == null ? 0 : (1 + Math.max(getTreeDepth(root.left), getTreeDepth(root.right)));
    }


    private static void writeArray(TreeNode currNode, int rowIndex, int columnIndex, String[][] res, int treeDepth) {
        // 保证输入的树不为空
        if (currNode == null) return;
        // 先将当前节点保存到二维数组中
        res[rowIndex][columnIndex] = String.valueOf(currNode.val);

        // 计算当前位于树的第几层
        int currLevel = ((rowIndex + 1) / 2);
        // 若到了最后一层，则返回
        if (currLevel == treeDepth) return;
        // 计算当前行到下一行，每个元素之间的间隔（下一行的列索引与当前元素的列索引之间的间隔）
        int gap = treeDepth - currLevel - 1;

        // 对左儿子进行判断，若有左儿子，则记录相应的"/"与左儿子的值
        if (currNode.left != null) {
            res[rowIndex + 1][columnIndex - gap] = "/";
            writeArray(currNode.left, rowIndex + 2, columnIndex - gap * 2, res, treeDepth);
        }

        // 对右儿子进行判断，若有右儿子，则记录相应的"\"与右儿子的值
        if (currNode.right != null) {
            res[rowIndex + 1][columnIndex + gap] = "\\";
            writeArray(currNode.right, rowIndex + 2, columnIndex + gap * 2, res, treeDepth);
        }
    }


    public static void show(TreeNode root) {
        if (root == null) System.out.println("EMPTY!");
        // 得到树的深度
        int treeDepth = getTreeDepth(root);

        // 最后一行的宽度为2的（n - 1）次方乘3，再加1
        // 作为整个二维数组的宽度
        int arrayHeight = treeDepth * 2 - 1;
        int arrayWidth = (2 << (treeDepth - 2)) * 3 + 1;
        // 用一个字符串数组来存储每个位置应显示的元素
        String[][] res = new String[arrayHeight][arrayWidth];
        // 对数组进行初始化，默认为一个空格
        for (int i = 0; i < arrayHeight; i++) {
            for (int j = 0; j < arrayWidth; j++) {
                res[i][j] = " ";
            }
        }

        // 从根节点开始，递归处理整个树
        // res[0][(arrayWidth + 1)/ 2] = (char)(root.val + '0');
        writeArray(root, 0, arrayWidth / 2, res, treeDepth);

        // 此时，已经将所有需要显示的元素储存到了二维数组中，将其拼接并打印即可
        for (String[] line : res) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < line.length; i++) {
                sb.append(line[i]);
                if (line[i].length() > 1 && i <= line.length - 1) {
                    i += line[i].length() > 4 ? 2 : line[i].length() - 1;
                }
            }
            System.out.println(sb.toString());
        }
    }

    public static TreeNode findNode(TreeNode root, int val) {
        if (root == null || root.val == val) {
            return root;
        } else {
            TreeNode left = findNode(root.left, val);
            TreeNode right = findNode(root.right, val);
            if (left != null) return left;
            return right;
        }
    }

    // 测试方法
    public static void main(String[] args) {
        // 测试用例：1,2,3,4,5,-1,-1（3的左右子节点为空）
        int[] levelOrder = {1, 2, 3, 4, 5, -1, -1};
        TreeNode root = buildTree(levelOrder);
        System.out.println("二叉树结构：");
        show(root);
    }
}
